<%--
  Created by IntelliJ IDEA.
  User: jali
  Date: 2018/12/4
  Time: 23:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="C" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <%--
        web路径：
        不以/开始的相对路径，找资源，以当前资源的路径为基准，经常容易出问题。
        以/开始的相对路径，找资源，以服务器的路径为标准（http://localhost:8080）
        http://localhost:8080/curd
    --%>
    <script type="text/javascript" src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

<!-- Modal -->
<div class="modal fade" id="empEditModel" tabindex="-1" role="dialog" aria-labelledby="empEditModelLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="empEditModelLabel">添加员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="inputEmpName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update_static"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="email_update_input" placeholder="123@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">sex</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="sex" id="sex_update_radio_M" value="M"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="sex" id="sex_update_radio_F" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="deptId_update" name="deptid">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="empAddModel" tabindex="-1" role="dialog" aria-labelledby="empAddModelLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="empAddModelLabel">添加员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="inputEmpName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="inputEmpName" placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="inputEmail" placeholder="123@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">sex</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="sex" id="sexRadio1" value="M"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="sex" id="sexRadio2" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="deptid" name="deptid">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>ssm-crud</h1>
        </div>
    </div>

    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-10">
            <button class="btn btn-primary" id="emp_add_btn">新增</button>
            <button class="btn btn-danger" id="emp_del_btn">删除</button>
        </div>
    </div>

    <%--显示表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="check_all"></th>
                        <th>#</th>
                        <th>name</th>
                        <th>sex</th>
                        <th>email</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <%--分页--%>
    <div class="row">
        <%--分页文字信息--%>
        <div class="col-md-6" id="page_info_area">
        </div>

        <%--分页条信息--%>
        <div class="col-md-6" id="page_nav_area">

        </div>
    </div>


</div>
<script type="text/javascript">

    //全局变量总记录数
    var recordTotal;
    //当前页码
    var pageNum;

    //1、页面加载完成后，直接去发送ajax请求，要到分页数据
    $(function () {
        //页面第一次加载
        to_page(1);
    });

    function to_page(pn) {
        $.ajax({
            url:"${APP_PATH}/emps",
            data:"pn="+pn,
            type:"get",
            success:function (result) {
                console.log(result);
                //1、解析并显示员工数据
                build_taskItem_table(result);
                //2、解析并显示分页信息
                build_page_info(result);
                //3、解析并显示分页
                build_page_nav(result);
            }
        });
    }

    function build_taskItem_table(result) {
        $("#emps_table tbody").empty();
        $("#check_all").prop("checked",false);
        var emps = result.extend.pageInfo.list;
        $.each(emps,function (index,item) {
            var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td>");
            var empIdTd = $("<td></td>").append(item.id);
            var nameTd = $("<td></td>").append(item.empName);
            var sexTd = $("<td></td>").append(item.sex=="M"?"男":"女");
            var emailTd = $("<td></td>").append(item.email);
            var deptNameTd = $("<td></td>").append(item.dept.deptname);
            var editBtn = $("<button></button>").addClass("btn btn-primary edit_btn").append("编辑");
            editBtn.attr("edit-id",item.id);
            var delBtn = $("<button></button>").addClass("btn btn-danger del_btn").append("删除");
            delBtn.attr("edit-id",item.id);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);
            $("<tr></tr>").append(checkBoxTd).append(empIdTd).append(nameTd).append(sexTd).append(emailTd).append(deptNameTd).append(btnTd)
                .appendTo("#emps_table tbody");
        })
    }
    //解析分页显示信息
    function build_page_info(result) {
        $("#page_info_area").empty();
        $("#page_info_area").append("当前第"+result.extend.pageInfo.pageNum+"页 共"+result.extend.pageInfo.pages+"页 总"+result.extend.pageInfo.total+"条记录");
        recordTotal = result.extend.pageInfo.total;
        pageNum = result.extend.pageInfo.pageNum;
    }
    function build_page_nav(result) {
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        //首页
        var firstLi = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append("首页")));

        //如果没有上一页
        if(!result.extend.pageInfo.hasPreviousPage){
            firstLi.addClass("disabled");
        }else{
            //上一页
            var prevLi = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append("&laquo;")));
            prevLi.click(function () {
                to_page(result.extend.pageInfo.pageNum - 1);
            });
            firstLi.click(function () {
                to_page(1);
            });
        }
        ul.append(firstLi).append(prevLi);;

        //显示的页码数
        var nums = result.extend.pageInfo.navigatepageNums;
        $.each(nums,function (index,item) {
            var li = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append(item)));
            if(result.extend.pageInfo.pageNum == item){
                li.addClass("active");
            }
            li.click(function () {
                to_page(item)
            });
            ul.append(li);
        })

        //如果没有下一页
        var lastLi = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append("末页")));
        if(!result.extend.pageInfo.hasNextPage){
            lastLi.addClass("disabled");
        }else{
            var nextLi = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append("&raquo;")));
            ul.append(nextLi);
            nextLi.click(function () {
                to_page(result.extend.pageInfo.pageNum + 1);
            });
            lastLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            })
        }
        ul.append(lastLi);
        var nav = $("<nav></nav>").append(ul).appendTo("#page_nav_area");
    };

    function reset_form(ele){
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }

    //点击新增弹出模态框
    $("#emp_add_btn").click(function () {
        reset_form("#empAddModel form");
        //发送ajax请求获取部门信息
        getDepts("#deptid");
        $('#empAddModel').modal({
            //点击框外的区域不会关闭弹框
            backdrop : "static"
        });
    });

    function getDepts(ele) {
        $(ele).empty();
        $.ajax({
            url:"${APP_PATH}/depts",
            type:"GET",
            success:function (result) {
                //{code: 200, msg: "处理成功！", extend: {depts: [{id: 1, deptname: "开发部"}, {id: 2, deptname: "人事部"}]}}
                //console.log(result);
                $.each(result.extend.depts,function () {
                    $(ele).append($("<option></option>").append(this.deptname).attr("value",this.id));
                })
            }
        });
    }

    function validate_add_form(){
        var empName = $("#inputEmpName").val();
        //1、拿到要校验的数据，使用正则表达式
        var regName = /(^[a-zA-Z0-9_-]{3,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        if(!regName.test(empName)){
            show_validate_smg("#inputEmpName","error","用户名必须是2-5位中文或者3-16位英文和数字的组合");
            return false;
        }else{
            checkUser(empName);
        }
        var email = $("#inputEmail").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            show_validate_smg("#inputEmail","error","邮箱格式不正确");
            return false;
        }else{
            show_validate_smg("#inputEmail","success","");
        }
        return true;
    }

    function show_validate_smg(ele,status,msg){
        $(ele).parent().removeClass("has-error has-success");
        if("error"==status){
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }else if("success"==status){
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        }
    }

    $("#emp_save_btn").click(function () {
        /*
        URI:
            /emp/{id}  GET查询员工
            /emp       POST保存员工
            /emp/{id}  PUT修改稿员工
            /emp/{id}  DELETE删除员工
         */
        //1、模态框中填写的表单数据提交到服务器进行保存
        //1）先对要提交给服务器的数据进行校验
        if(!validate_add_form()){
            return false;
        }
        //2、发送ajax请求保存员工
        $.ajax({
            url:"${APP_PATH}/emp",
            type:"POST",
            data:$("#empAddModel form").serialize(),
            success:function (result) {
                $("#empAddModel").modal("hide");
                to_page(recordTotal);
            }
        })
    });

    $("#inputEmpName").change(function () {
        //发送ajax请求用户名是否可用
        var empName = this.value;
        checkUser(empName);
    });

    function checkUser(empName) {
        $.ajax({
            url:"${APP_PATH}/checkUser",
            type:"POST",
            data:"empName="+empName,
            success:function (result) {
                if("100"==result.code){
                    show_validate_smg("#inputEmpName","success","用户名可用");
                    $("#emp_save_btn").attr("ajax-va","success");
                }else{
                    show_validate_smg("#inputEmpName","error",result.extend.va_msg);
                    $("#emp_save_btn").attr("ajax-va","error");
                }
            }
        })
    }

    //1.我们是按钮创建之前就绑定了click，所以绑定不上
    //1)、可以在创建按钮的时候绑定，2)、绑定点击.live()
    //jquery新版没有live，使用on进行替代
    $(document).on("click",".edit_btn",function () {
        reset_form("#empEditModel form");
        //1.查出员工信息，显示员工信息
        //2.查出部门信息，并显示部门列表
        getDepts("#deptId_update");
        var id = $(this).attr("edit-id");
        getEmp(id);
        $("#emp_update_btn").attr("edit-id",id);
        $("#empEditModel").modal({
            //点击框外的区域不会关闭弹框
            backdrop : "static"
        });
    });
    
    function getEmp(id) {
        $.ajax({
            url:"${APP_PATH}/emp/"+id,
            type:"GET",
            success:function (result) {
                var empDate = result.extend.emp;
                $("#empName_update_static").text(empDate.empName);
                $("#email_update_input").val(empDate.email);
                $("#empEditModel input[name=sex]").val([empDate.sex]);
                $("#empEditModel select").val([empDate.deptid]);
            }
            
        })
    }
    
    //点击更新，更新员工信息
    $("#emp_update_btn").click(function () {
        //验证邮箱是否合法
        //1.校验邮箱信息
        var email = $("#email_update_input").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            show_validate_smg("#email_update_input","error","邮箱格式不正确");
            return false;
        }else{
            show_validate_smg("#email_update_input","success","");
        }
        //2.发送ajax请求保存更新的员工数据
        $.ajax({
            url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
            type:"PUT",
            data:$("#empEditModel form").serialize(),
            success:function (result) {
                //1、关闭对话框
                $("#empEditModel").modal("hide");
                //2、回到本页面
                to_page(pageNum);
            }
        })
    });

    //单个删除
    $(document).on("click",".del_btn",function () {
        //1.弹出是否确认删除对话框
        var empName = $(this).parents("tr").find("td:eq(2)").text();
        if(confirm("确认删除【" + empName + "】吗？")){
            //确认，发送ajax删除
            var id = $(this).attr("edit-id");
            $.ajax({
                url:"${APP_PATH}/emp/"+id,
                type:"DELETE",
                success:function (result) {
                    to_page(pageNum);
                }
            })
        }
    });

    $("#check_all").click(function () {
        //attr获取checked的是underfined
        //attr：获取自定义属性的值
        //prop修改和读取dom原生属性的值
        $(".check_item").prop("checked",$(this).prop("checked"));
    });

    $(document).on("click",".check_item",function () {
        var flag = $(".check_item:checked").length==$(".check_item").length;
        $("#check_all").prop("checked",flag);
    });

    //点击全部删除，批量删除
    $("#emp_del_btn").click(function () {
        var empNames = "";
        var ids = "";
        $.each($(".check_item:checked"),function () {
          empNames += $(this).parents("tr").find("td:eq(2)").text() + "，";
          ids += $(this).parents("tr").find("td:eq(1)").text() + "-";
        })
        if(confirm("确认删除【"+empNames.substring(0,empNames.length-1)+"】吗？")){
            //发送ajax请求删除
            $.ajax({
                url:"${APP_PATH}/emp/"+ids,
                type:"DELETE",
                success:function (result) {
                    to_page(pageNum);
                }
            })
        }
    });

</script>
</body>
</html>
